package org.example.douban.parser;

import org.apache.log4j.Logger;
import org.example.douban.tool.RandomCookie;
import org.example.douban.tool.SystemTool;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;

public class NetConnectionImpl implements NetConnection {
	private Logger log = Logger.getLogger(NetConnectionImpl.class.getName());
	private int retryCount = SystemTool.RETRY_COUNT;
	private int SLEEP_TIME = SystemTool.SLEEP_TIME;
	private String user_agent = SystemTool.USER_AGENT;

	// 代理隧道验证信息
	final static String ProxyUser = "H7088O24GU71RXVD";
	final static String ProxyPass = "1D60C3D7538C9DEE";

	// 代理服务器
	final static String ProxyHost = "http-dyn.abuyun.com";
	final static Integer ProxyPort = 9020;
	// 设置IP切换头
	final static String ProxyHeadKey = "Proxy-Switch-Ip";
	final static String ProxyHeadVal = "yes";

	private String cookie = RandomCookie.getRandomCookie(11);

	public Document getDocument(String url) {
		Document doc = null;
		System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
		Authenticator.setDefault(new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication()
			{
				return new PasswordAuthentication(ProxyUser, ProxyPass.toCharArray());
			}
		});//不开代理，需要注释
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyHost, ProxyPort));//不开代理，需要注释
		try {
			doc = Jsoup.connect(url).userAgent(user_agent)
					.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
					.header("scheme", "https").header("version", "HTTP/1.1")
					.header("accept-encoding", "gzip, deflate, sdch").header("accept-language", "zh-CN,zh;q=0.8")
					.header("cookie", "bid=" + cookie).header("cache-control", "max-age=0")
					.header(ProxyHeadKey, ProxyHeadVal)//不开代理，需要注释
					.proxy(proxy)//不开代理，需要注释
					// 忽略证书校验
					.validateTLSCertificates(false)
					.get();

		} catch (Exception e) {
			log.info("[ERROR] Excepion is:" + e.getMessage());
			try {
				Thread.sleep(SLEEP_TIME);
			} catch (InterruptedException e1) {
				// e1.printStackTrace();
			}

			retryCount--;
			if (retryCount > 0) {
				log.info("[INFO] the cookie is blocked,reset the cookie...");
				cookie = RandomCookie.getRandomCookie(11);
				getDocument(url);
			} else {
				log.info("[ERROR]Connection is failed:"+e.getMessage());
			}

		}
		return doc;

	}

}
